package com.zkyc.framework.common.utils;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class EncryptPublicKey {
    public static void main(String[] args) {
        // 公钥字符串,这里直接赋值了，当然一般不会这么写，把公钥放在一个数据文件或者配置里面去获取
        String publicKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCJUZ+ud0MrgohvB3XGp2zHbj1fz/fF4++So8Ji7vkAyMnx0Jws6l8k1MR6N1oIEVhg69+MDjXWe70MeeuV4mkm5Sim+euJ8dVvf+ZwTKG+iSyu0JLAmMdf58X9dgQHYEEB0d/AIjfaOqqYhbkowuK0vnqqEs7TLOM3nks9lTeWIwIDAQAB";
        try {
            // 把公钥字符串转换成对象
            byte[] publicKeyBy = Base64.getDecoder().decode(publicKeyStr.getBytes());
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey publicKey = keyFactory.generatePublic(new X509EncodedKeySpec(publicKeyBy));

            // 以上获得的PublicKey可以固化下来，只要秘钥不变，就可以一直使用，但是下面的cipherPublic 不要固化！因为他不是线程安全的，如果使用同一个cipherPublic 并发访问时可能会抛出异常javax.crypto.IllegalBlockSizeException: Data must not be longer than 128 bytes
            Cipher cipherPublic = Cipher.getInstance("RSA");
            // 设置为加密模式并设置公钥
            cipherPublic.init(Cipher.ENCRYPT_MODE, publicKey);

            // 定义一个发送的数据
            String sendMsg = "123456";
            // 获得加密的byte[]
            byte[] encryptByte = cipherPublic.doFinal(sendMsg.toString().getBytes("UTF-8"));
            // 转变成字符串以进行传输
            String strKey = Base64.getEncoder().encodeToString(encryptByte);
            System.out.println("加密后的数据为：" + strKey);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
